package com.bupt.smart.ui.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.location.Address;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Toast;

import com.bupt.smart.model.recAddress;
import com.bupt.smart.network.APIManager;
import com.bupt.smart.smart.R;
import com.bupt.smart.utils.MarketHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;

import java.security.Policy;
import java.util.HashMap;
import java.util.Map;

import cz.msebera.android.httpclient.Header;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by WWL on 2016/6/10.
 * 编辑收货地址
 */
public class AddAddressActivity extends AppCompatActivity implements View.OnClickListener{
    int USERID = 2; //从登陆信息中获取
    Intent getIntent = null;
    EditText edittext_name;
    EditText edittext_tel;
    EditText edittext_build;
    EditText edittext_house;
    ImageButton chosen;
    int Type;
    HashMap<String,String> map_address = new HashMap<String,String>();
    ImageView addaddr_back;
    protected void onCreate ( Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_addaddr);
        //初始化
        map_address.put("name", "");
        map_address.put("phonenumber", "");
        map_address.put("building", "");
        map_address.put("housenumber","");
        getIntent = getIntent();
        //获取组件
        addaddr_back = (ImageView)findViewById(R.id.addaddr_back);
        edittext_build = (EditText)findViewById(R.id.addaddr_textbuilding);
        edittext_house = (EditText)findViewById(R.id.addaddr_texthousenum);
        edittext_tel = (EditText)findViewById(R.id.addaddr_textphonenum);
        edittext_name = (EditText)findViewById(R.id.addaddr_textname);
        chosen = (ImageButton)findViewById(R.id.addaddr_chosen);
        Type = getIntent.getIntExtra("type",-1);//获取跳转类型：1 新建地址 2 编辑已有地址
        if(Type==2){    //显示已有地址
            InitAddress();
        }
        //返回地址页面
        addaddr_back.setOnClickListener(this);
        chosen.setOnClickListener(this);
        edittext_name.addTextChangedListener(new myTextWatch(1));
        edittext_tel.addTextChangedListener(new myTextWatch(2));
        edittext_build.addTextChangedListener(new myTextWatch(3));
        edittext_house.addTextChangedListener(new myTextWatch(4));
    }
    //显示需要编辑的地址
    public void InitAddress(){
        recAddress address = (recAddress)getIntent.getSerializableExtra("editAddress");
        String name = address.getName();
        String tel = address.getPhonenumber();
        String housenumber = address.getHousenumber();
        String building = address.getBuilding();
        //edittext显示地址
        edittext_name.setText(name);
        edittext_build.setText(building);
        edittext_tel.setText(tel);
        edittext_house.setText(housenumber);
        map_address.put("name",name);
        map_address.put("phonenumber", tel);
        map_address.put("building", building);
        map_address.put("housenumber",housenumber);
        changeState();
    }
    //事件监听
    @Override
    public void onClick(View v){
        switch(v.getId()){
            case R.id.addaddr_back:{
                Intent intent = new Intent(AddAddressActivity.this,AddressActivity.class);
                intent.putExtras(getIntent);
                AddAddressActivity.this.startActivity(intent);
            }break;
            case R.id.addaddr_chosen:{
                //写入数据库，跳转回收货地址界面
                if(changeState()){
                    //异步写入数据库
                    addAddress();
                }
                else{
                    Toast toast = Toast.makeText(this.getApplicationContext(),"请填完整",Toast.LENGTH_SHORT);
                    toast.setGravity(Gravity.TOP|Gravity.CENTER,0,150);
                    toast.show();

                }
            }break;
            default:{}
        }
    }
    //改变对勾状态
    public boolean changeState(){
        Log.i("aaaa", map_address.get("name") + "6");
        if((!map_address.get("name").equals(""))&&(!map_address.get("phonenumber").equals(""))&&
                (!map_address.get("building").equals(""))&&(!map_address.get("housenumber").equals(""))){
            chosen.setImageResource(R.mipmap.btn_icon_chosenresult3);
            return true;
        }
        else{
            chosen.setImageResource(R.mipmap.btn_icon_chosenresult2);
            return false;
        }

    }

    //自定义TextWatch
    class myTextWatch implements TextWatcher{
        int type;
        int curlen;
        public myTextWatch(int type){
            this.type = type;
        }
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            if((curlen==1)&&(after==0)) { //清空edit数据
                switch (type) {
                    case 1: {
                        map_address.put("name", "");
                        changeState();
                    }
                    break;
                    case 2: {
                        map_address.put("phonenumber", "");
                        changeState();
                    }
                    break;
                    case 3: {
                        map_address.put("building", "");
                        changeState();
                    }
                    break;
                    case 4: {
                        map_address.put("housenumber", "");
                        changeState();
                    }
                    break;
                    default: {
                    }
                }
                Log.i("s.length", "s.length:" + s.length() + "after:" + after + "name" + AddAddressActivity.this.edittext_name.getText().toString());
            }
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            Log.i("s",s.toString());
            curlen = s.length();
            switch(type){
                case 1:{
                    map_address.put("name",s.toString());
                    changeState();
                }break;
                case 2:{
                    map_address.put("phonenumber",s.toString());
                    changeState();
                }break;
                case 3:{
                    map_address.put("building",s.toString());
                    changeState();
                }break;
                case 4:{
                    map_address.put("housenumber",s.toString());
                    changeState();
                }break;
                default:{}
            }
        }
        @Override
        public void afterTextChanged(Editable s) {

        }
    }
    public void addAddress(){
        recAddress address = new recAddress();
        address.setName(map_address.get("name"));
        address.setBuilding(map_address.get("building"));
        address.setHousenumber(map_address.get("housenumber"));
        address.setPhonenumber(map_address.get("phonenumber"));
        address.setId(getIntent.getIntExtra("addressID", -1));
        address.setUserid(USERID);
        Call<Map<String,Boolean>> call = APIManager.getMarketAPI().editAddress(Type,address);
        call.enqueue(new Callback<Map<String,Boolean>>() {
            @Override
            public void onResponse(Call<Map<String,Boolean>> call, Response<Map<String,Boolean>> response) {
                if(response.body()!=null){
                    if(response.body().get("result") == true){
                        Intent intent = new Intent(AddAddressActivity.this, AddressActivity.class);
                        intent.putExtras(getIntent);
                        AddAddressActivity.this.startActivity(intent);
                    }
                     else{
                        Toast toast = Toast.makeText(AddAddressActivity.this,"保存地址失败！",Toast.LENGTH_LONG);
                        toast.show();
                    }
                }
            }
            @Override
            public void onFailure(Call<Map<String,Boolean>> call, Throwable t) {
                Toast toast = Toast.makeText(AddAddressActivity.this,"连接服务器失败！",Toast.LENGTH_LONG);
                toast.show();
            }
        });
    }
    /*
    * 异步发送数据到后台
    *
    * */
//    public void AsyncInsertDB(){
//        MarketHttpClient client = new MarketHttpClient();
//        RequestParams params = new RequestParams();
//        params.put("name",map_address.get("name"));
//        params.put("phonenumber",map_address.get("phonenumber"));
//        params.put("building",map_address.get("building"));
//        params.put("housenumber",map_address.get("housenumber"));
//        params.put("Userid",USERID);
//        params.put("id",getIntent.getIntExtra("addressID",-1));
//        params.put("type", Type);
//        client.post("mobile/address_add", params, new AsyncHttpResponseHandler() {
//            @Override
//            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
//                Intent intent = new Intent(AddAddressActivity.this, AddressActivity.class);
//                intent.putExtras(getIntent);
//                AddAddressActivity.this.startActivity(intent);
//            }
//
//            @Override
//            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
//
//                Toast toast = Toast.makeText(getApplicationContext(), "连接服务器失败", Toast.LENGTH_LONG);
//                toast.show();
//            }
//        });
//    }

}
